<script>
import BaseNode from "../../mixins/node.js";
import { VueDraggable, vDraggable } from "vue-draggable-plus";
import OperatingPatientNode from "./OperatingPatientNode.vue";
import OperatingEmptyNode from "./OperatingEmptyNode.vue";
import $ from "jquery";
const updateWrapEls = new Set();
export default {
  inject: ["getManager"],
  props: {
    showType: String,
    activedId: String,
    scrollOffset: {
      type: Object,
      default: () => ({}),
    },
    config: Object,
    isTransitionRunning: Boolean,
  },
  mixins: [BaseNode],
  data() {
    return {
      isGroup: true,
      height: null,
      dataList: [],
      draging: false,
    };
  },
  computed: {
    actived() {
      return (
        this.dataList.findIndex(
          (item) => item[this.config.idKey || "id"] === this.activedId
        ) > -1
      );
    },
    activedInGroupIndex() {
      return this.dataList.findIndex(
        (item) => item[this.config.idKey || "id"] === this.activedId
      );
    },
    width() {
      let index = this.dataList.length - 1;
      let activedIndex = this.activedInGroupIndex;
      return this.showType === "fix"
        ? index * 50 +
            (index > activedIndex && activedIndex > -1 ? 340 : 0) +
            365
        : null;
    },
    dotOffsetStyle() {
      let x = this.scrollOffset?.scrollLeft || 0;
      if (this.showType !== "group") {
        return {
          left: Math.max(x - 9, -9) + "px",
        };
      }
      return {};
    },
  },
  watch: {
    data: {
      handler() {
        this.dataList = [...(this.data || [])];
      },
      immediate: true,
    },
    isTransitionRunning() {
      if (
        this.showType === "fix" &&
        this.$refs.dragWrap.$el.children.length > 0
      ) {
        let activedChildrens =
          Math.max(
            ...[...this.$refs.dragWrap.$el.children].map(
              (item) => item.offsetHeight
            )
          ) || 0;
        this.height = Math.max(145, activedChildrens + 1);
      } else {
        this.height = null;
      }
    },
    height() {
      clearInterval(this.timer);
      this.doneAnimate = true;
      let old = window.performance.now();
      let execFn = () => {
        this.getManager()?.updateEdges();
        let now = window.performance.now();
        if (now - old < 350) {
          window.requestAnimationFrame(execFn);
        }
      };
      this.$nextTick(() => {
        window.requestAnimationFrame(execFn);
      });
    },
  },
  components: {
    VueDraggable,
    OperatingPatientNode,
    OperatingEmptyNode,
  },
  directives: {
    vDraggable,
  },
  methods: {
    getFixStyle(index) {
      if (this.showType === "fix") {
        let activedIndex = this.activedInGroupIndex;
        return {
          left: `${
            index * 50 + (index > activedIndex && activedIndex > -1 ? 340 : 0)
          }px`,
          zIndex: index * 2,
        };
      }
      return {};
    },
    nodeClickHandler(...args) {
      this.$emit("clickedHandler", ...args);
    },
    dragStartHandler(evt) {
      this.draging = true;
      let { oldIndex, item } = evt;
      this.$emit("clickedHandler", null, false);
      this.$nextTick(() => {
        $(item).addClass("schedule-ghost");
        $(item)
          .find(".drag-tip-number")
          .html(`<span>${oldIndex + 1}</span>`);
      });
    },
    dragEndHandler() {
      setTimeout(() => {
        this.getManager()?.updateEdges();
        this.draging = false;
      }, 50);
    },
    sortHandler(evt) {
      // 保存数据调用api接口
      // 多选拖动
      const dragList = this.dataList[evt.newDraggableIndex];
      if (Array.isArray(dragList)) {
        this.dataList.splice(evt.newDraggableIndex, 1, ...dragList);
      }
      this.dataList = this.dataList.map((item) => {
        return {
          ...item,
          [this.config.pIdKey || "pid"]: this.pid,
        };
      });
    },
    dragChangeHandler(evt) {
      this.getManager()?.updateEdges();

      let { from, item, newIndex, to } = evt;
      $(item)
        .find(".drag-tip-number")
        .html(`<span>${newIndex + 1}</span>`);
      if (this.showType === "fix") {
        let updates = new Set();

        if (updateWrapEls.size) {
          updates.add(...updateWrapEls);
          updateWrapEls.clear();
        }
        updates.add(from);
        updates.add(to);
        ![...updates].forEach((item) => this.updateElsPos([...item.children]));
        updateWrapEls.add(to);
      }
    },
    updateElsPos(els) {
      let hasActived = false;
      els.forEach((item, index) => {
        let id = item.getAttribute("data-id");
        let style = {
          left: `${index * 50 + (hasActived ? 340 : 0)}px`,
          zIndex: index * 2,
        };
        if (id === this.activedId) {
          hasActived = true;
        }
        for (let p in style) {
          item.style[p] = style[p];
        }
      });
    },
  },
};
</script>
<template>
  <div
    :class="['operating-group', showType]"
    ref="patientGroup"
    :style="
      Object.assign(
        {},
        this.showType === 'fix' && height ? { height: height + 'px' } : {},
        width ? { width: width + 'px' } : {}
      )
    "
  >
    <operating-empty-node
      class="card-node"
      v-if="dataList.length === 0"
      :id="`${id}_empty`"
      :pid="pid"
      :activedId="activedId"
      :data="{}"
      :showType="showType"
    />
    <div class="sch-dot --left" ref="leftDot" :style="dotOffsetStyle"></div>
    <VueDraggable
      class="drag-wrap"
      :data-id="id"
      v-model="dataList"
      animation="150"
      ref="dragWrap"
      ghostClass="schedule-ghost"
      dragClass="shedule-sortable-drag"
      group="patient"
      :forceFallback="false"
      :swapThreshold="4"
      @start="dragStartHandler"
      @end="dragEndHandler"
      @sort="sortHandler"
      @change="dragChangeHandler"
    >
      <div
        v-for="(item, index) in dataList"
        :class="['patient-wrap', draging ? 'draging' : '']"
        :key="item[config.idKey || 'id']"
        :style="getFixStyle(index)"
        :data-id="item[config.idKey || 'id']"
      >
        <operating-patient-node
          class="card-node"
          ref="nodeList"
          :id="item[config.idKey || 'id']"
          :pid="item[config.pidKey || 'pid']"
          :actived="item[config.idKey || 'id'] === activedId"
          :key="item[config.idKey || 'id']"
          :data="item"
          :positionIndex="index"
          :showType="showType"
          @clickedHandler="nodeClickHandler"
        />
      </div>
    </VueDraggable>
  </div>
</template>
<style lang="less">
.shedule-sortable-drag {
  .sch-dot {
    display: none;
  }
}
.schedule-ghost {
  .drag-tip-number {
    display: flex !important;
  }
  & > .card-node {
    & > .els-collapse-item {
      opacity: 0;
    }
    background: #eaf3ff;
    border-radius: 4px;
    padding-bottom: 0 !important;

    outline: 1px dashed #d9d9d9 !important;
    outline-offset: -1px;
  }
}
</style>
<style scoped lang="less">
.operating-group {
  position: relative;
  min-height: 145px;
  .drag-wrap {
    height: 100%;
    min-height: 125px;
  }
  &.link {
    // border-top: 1px solid #d8d8d8;
    padding-top: 10px;
    white-space: nowrap;
    .drag-wrap .patient-wrap {
      display: inline-block;
      vertical-align: top;
      margin-right: 10px;
    }
  }
  &.fix {
    // transition: height 0.1s linear;
    height: 145px;
    min-height: 145px;
    margin-top: 30px;
    min-width: 100%;
    ::v-deep .empty-node {
      top: 0;
    }
    .drag-wrap .patient-wrap {
      position: absolute;
      cursor: pointer;
      transition: opacity 0.3s, border 0.3s, background 0.3s, top 0.15s linear,
        left 0.15s, transform 0.15s;
      & > ::v-deep .card-node {
        position: relative;

        top: 0;
        transition: opacity 0.3s, border 0.3s, background 0.3s, top 0.15s linear,
          left 0.15s, transform 0.15s, padding-bottom 0.15s linear;
        // background: #fff;
        .els-collapse-item__header {
          display: flex;
        }

        &:hover {
          padding-bottom: 30px;
          top: -30px;
          // transform: scale(1.2);
          // transform-origin: 0 100%;
          width: 380px;
          .els-collapse-item .els-collapse-item__header {
            border-color: #1677ff;
          }
          .fix-type-number {
            display: flex;
            width: 20px;
          }
        }
        &.actived {
          top: 0px;
          padding-bottom: 0px;
          width: 380px;
          z-index: 400 !important;
          .fix-type-number {
            display: flex;
            width: 20px;
          }
        }
      }
      &.draging::after {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 999;
      }
    }
  }
  .empty-operating {
    width: 360px;
    height: 125px;
    border: 1px dashed #d8d8d8;
    position: absolute;
    top: 0;
    left: 0;
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.02);
    font-size: 12px;
    display: flex;
    color: rgba(0, 0, 0, 0.45);
    pointer-events: none;
    align-items: center;
    justify-content: center;
  }
  .patient-wrap {
    margin-bottom: 10px;
  }
  .card-node {
    overflow: visible;
    ::v-deep {
      .els-collapse-item {
        // border: 1px solid #ebeef5;
        border-radius: 4px;
        outline: 1px solid #d8d8d8;
        outline-offset: -1px;
        &:hover {
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  .sch-dot {
    // width: 0 !important;
    // height: 0 !important;
    margin-top: 0 !important;
    top: 60px !important;
  }
}
</style>
